#include "mainwindow.h"
#include "ui_mainwindow.h"
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex MessageOutput_Mutex;
    MessageOutput_Mutex.lock();
    (void)context;
    QByteArray localMsg = msg.toLocal8Bit();

    //信息分类
    QString strMsg("");

    switch(type)
    {
        case QtDebugMsg:
            strMsg = QString("Debug:");
            break;

        case QtInfoMsg:
            strMsg = QString("Info:");
            break;

        case QtWarningMsg:
            strMsg = QString("Warning:");
            break;

        case QtCriticalMsg:
            strMsg = QString("Critical:");
            break;

        case QtFatalMsg:
            strMsg = QString("Fatal:");
            break;

        default:
            break;
    }

    // 设置输出信息格式
    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString strMessage = QString("%1 %2 %3").arg(strDateTime, strMsg, localMsg.constData());

    try
    {
        pw->COM_Text->moveCursor(QTextCursor::End);
        pw->COM_Text->insertPlainText(strMessage);
        MessageOutput_Mutex.unlock();
    }
    catch(int i)
    {
        MessageOutput_Mutex.unlock();
    }
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    pw = this;
    this->COM_Text = this->ui->textEdit;
    qRegisterMetaType<QTextCursor>("QTextCursor");
    qInstallMessageHandler(myMessageOutput);
    File_List.clear();
    qDebug() << "Init\n";
    current_dir_path = QCoreApplication::applicationDirPath();
    // qDebug()<<dir_path<<"\n";
    astyle_path = current_dir_path + "/astyle.exe";
    QFileInfo fileInfo(astyle_path);

    if (fileInfo.isFile())
    {
        qDebug() << astyle_path << "\n";
    }
    else
    {
        qDebug() << "astyle.exe cannot open\n";
    }

    this->ui->comboBox->addItem("缩进空格2");
    this->ui->comboBox->addItem("缩进空格4");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_textEdit_textChanged()
{
    this->ui->textEdit->moveCursor(QTextCursor::End);
}

void MainWindow::on_pushButton_clicked()
{
    this->ui->textEdit->clear();
}

void MainWindow::show_File_List()
{
    uint32_t len = File_List.size();
    uint32_t i = 0;
    // 使用QSet去重（保持原有顺序）
    QSet<QString> uniquePaths;
    QStringList filteredList;

    for (i = 0; i < len; i++)
    {
        if (!uniquePaths.contains(File_List[i]))
        {
            uniquePaths.insert(File_List[i]);
            filteredList.append(File_List[i]);
        }
    }

    File_List = filteredList;
    len = File_List.size();
    this->ui->textEdit_3->clear();
    QString content;

    for(i = 0; i < len; i++)
    {
        content += File_List[i] + "\n";
    }

    ui->textEdit_3->setPlainText(content);
    this->ui->textEdit_3->moveCursor(QTextCursor::End);
}

void MainWindow::on_pushButton_2_clicked()
{
    QStringList pathList = QFileDialog::getOpenFileNames(this, "选择文件", current_dir_path, "c/c++(*.c *.cpp *.h *.hpp *.cc *.cxx *.hxx *.tpp *.tpl *.c++ *.C *.ii *.inl *.ipp *.inc);;text(*.txt *.log *.ini *.conf *.env *.md *.csv *.tsv *.xml *.json *.yml *.yaml *.bat *.sh *.gitignore *.htaccess);;All(*.*)");
    this->ui->lineEdit->clear();
    const int len = pathList.size();
    int i = 0;
    QString path = "";

    if (len)
    {
        current_dir_path = pathList[0];

        for(i = 0; i < len; i++)
        {
            path = pathList[i];
            this->ui->lineEdit->setText(path);
            File_List.append(path);

            if(i == (len - 1))
            {
                QFile file(path);//创建文件对象

                if (file.open(QIODevice::ReadOnly))//只读方式打开
                {
                    QString content = file.readAll();//读取内容
                    this->ui->textEdit_2->setText(content);
                    file.close();//关闭文件
                }
                else
                {
                    qDebug() << "Failed to open file\n";//showMessage("文件打开失败")
                }
            }
        }

        this->show_File_List();
    }
    else
    {
        qDebug() << "No File\n";
    }
}


void MainWindow::on_pushButton_3_clicked()
{
    this->ui->textEdit_3->clear();
    this->ui->textEdit_2->clear();
    this->ui->lineEdit->clear();
    File_List.clear();
}


void MainWindow::on_pushButton_4_clicked()
{
    const int len = File_List.size();

    if(len == 0)
    {
        qDebug() << "No File\n";
        return;
    }

    int i = 0;
    QString path;
    QString cmd;
    QStringList arg;
    arg.clear();
    arg.append("");
    show_File_List();

    if(this->ui->c1->checkState())
    {
        arg.append("--style=allman");
    }

    if(this->ui->c2->checkState())
    {
        arg.append("-p");
    }

    if(this->ui->c3->checkState())
    {
        arg.append("-S");
    }

    if(this->ui->c4->checkState())
    {
        arg.append("-f");
    }

    if(this->ui->c5->checkState())
    {
        arg.append("-xW");
    }

    if(this->ui->c6->checkState())
    {
        arg.append("-w");
    }

    if(this->ui->c7->checkState())
    {
        arg.append("-xw");
    }

    if(this->ui->comboBox->currentIndex())
    {
        arg.append("-s4");
    }
    else
    {
        arg.append("-s2");
    }

    if(this->ui->c0->checkState())
    {
        arg.append("-n");
    }

    for(i = 0; i < len; i++)
    {
        path = File_List[i];
        qDebug() << "Trans style..." << path << "\n";
        cmd = astyle_path;
        arg[0] = path;
        shell.execute(cmd, arg);
        shell.waitForFinished(); //等待shell命令执行完成
        qDebug() << "Done\n";

        QFile file(path);//创建文件对象

        if(i == (len - 1))
        {
            if (file.open(QIODevice::ReadOnly))//只读方式打开
            {
                QString content = file.readAll();//读取内容
                this->ui->textEdit_2->setText(content);
                file.close();//关闭文件
            }
            else
            {
                qDebug() << "Failed to open file\n";//showMessage("文件打开失败")
            }
        }
    }

}
